package com.xizi.lotterySystem.service.activitystatus.operator;

import com.xizi.lotterySystem.common.exception.ServiceException;
import com.xizi.lotterySystem.common.exception.errorCode.ServiceErrorCodeConstants;
import com.xizi.lotterySystem.dao.mapper.ActivityPrizeMapper;
import com.xizi.lotterySystem.dao.dataobject.ActivityPrizeDO;
import com.xizi.lotterySystem.service.dto.ConvertActivityStatusDTO;
import com.xizi.lotterySystem.service.enumerate.ActivityPrizeStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class PrizeOperator extends AbstractActivityOperator {

    private static final Logger log = LoggerFactory.getLogger(PrizeOperator.class);
    @Autowired
    private ActivityPrizeMapper activityPrizeMapper;

    @Override
    public int sequence() {
        return 1;
    }

    @Override
    public Boolean needConvert(ConvertActivityStatusDTO param) {
        // 校验参数
        if (!param.getTargetActivityPrizeStatus().name().equalsIgnoreCase(ActivityPrizeStatusEnum.COMPLETED.name())){
            return false;
        }

        ActivityPrizeDO activityPrizeDO = activityPrizeMapper.selectByAPID(param.getActivityId(), param.getActivityPrizeId());
        if (activityPrizeDO == null) {
            log.error(ServiceErrorCodeConstants.ACTIVITY_PRIZE_NO_EXIST.getMessage()
                    + "activityId: {},activityPrizeId: {}",param.getActivityId(), param.getActivityPrizeId());
            throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_PRIZE_NO_EXIST);
        }

        // 校验奖品是否抽完    如抽完 则  更新状态
        if(activityPrizeDO.getPrizeAmount() != param.getUserIds().size()){
            log.error("奖品未抽完！");
            return false;
        }
        return true;
    }

    @Override
    public Boolean convert(ConvertActivityStatusDTO param) {
        Long activityId = param.getActivityId();
        Long prizeId = param.getActivityPrizeId();
        int row = activityPrizeMapper.updateStatusById(activityId,prizeId,param.getTargetActivityPrizeStatus());
        return row == 1;
    }
}
